package com.lxj.ticket.service.common.util;

import org.apache.commons.lang3.StringUtils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * @author 兴杰
 */
public class CommonUtil {

    private static final String KEY = "Zcy-lsjc";

    private static Key key = null;

    static {
        KeyGenerator keyGenerator = null;
        try {
            keyGenerator = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("加解密设置失败，请修改代码");
        }

        SecureRandom secureRandom = null;
        try {
            secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY.getBytes());

            //设置密钥长度
            keyGenerator.init(128, secureRandom);
            //生成密钥对象
            SecretKey secretKey = keyGenerator.generateKey();
            //获取密钥
            byte[] keyBytes = secretKey.getEncoded();
            //key转换
            key = new SecretKeySpec(keyBytes, "AES");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("加解密设置失败，请修改代码");
        }
    }

    /**
     * 将list进行分类
     *
     * @param allList
     * @param size
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> splitGroupList(List<T> allList, int size) {

        List<List<T>> result = new ArrayList<>();
        if (allList.size() > size) {

            int totalNumber = allList.size();
            int page = totalNumber / size;
            int offset = totalNumber % size;

            for (int i = 0; i < page; i++) {
                List<T> materialListInfos = allList.subList(i * size, (i + 1) * size);
                result.add(materialListInfos);
            }

            if (offset != 0) {
                List<T> materialListInfos = allList.subList(page * size, totalNumber);
                result.add(materialListInfos);
            }
        } else {
            result.add(allList);
        }
        return result;
    }

    /**
     * 将传入的字符串进行拼接
     *
     * @param params
     * @return
     */
    public static String joinStrings(String separator, String... params) {
        if (params.length == 0) {
            return null;
        } else {
            int i = 0;
            StringBuilder result = new StringBuilder();
            for (String param : params) {
                String dealParam = StringUtils.isBlank(param) ? "" : param;
                if (StringUtils.isBlank(separator)) {
                    result.append(dealParam);
                } else {
                    result.append(i == 0 ? dealParam : separator + dealParam);
                }

                i++;
            }
            return result.toString();
        }
    }

    /**
     * 设置响应为错误的json返回
     *
     * @param response
     * @param responseData
     */
//    public static void setResponseError(HttpServletResponse response, R responseData) {
//        response.reset();
//        response.setContentType("application/json");
//        response.setCharacterEncoding("utf-8");
//
//        try {
//            response.getWriter().println(JSON.toJSONString(responseData));
//        } catch (IOException e) {
//            response.setStatus(500);
//        }
//    }

    /**
     * 设置response返回的文件名
     * @param response
     * @param fileName
     */
//    public static void setResponseName(HttpServletResponse response,
//                                       String fileName) {
//        response.setCharacterEncoding("utf-8");
//        response.setContentType("application/vnd.ms-excel");
//        try {
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(fileName.toString(),"UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 加密字符串
     *
     * @param id
     * @return
     */
    public static String encodeAES(Long id) {
        //加密
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal((id + "").getBytes());
            return new String(Base64.getEncoder().encode(result));
        } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对id进行解码: 如果不匹配就返回null，拿到null就确定传过来的参数不是对的
     *
     * @param encodeString
     * @return
     */
    public static String decodeAES(String encodeString) {
        //初始化,设置为解密
        //加密
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);

            byte[] result = cipher.doFinal(Base64.getDecoder().decode(encodeString));
            return new String(result);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 前端参数处理：防止sql中查出来全部信息
     *
     * @param param
     * @return
     */
    public static String dealParam(String param) {

        if (StringUtils.isBlank(param)) {
            return param;
        }

        if (param.contains("%") || param.contains("/")
                || param.contains(".") || param.contains("\\")
                || param.contains("\"") || param.contains("'")) {
            return param.replace("\\", "\\\\")
                    .replace("%", "\\" + "%")
                    .replace("_", "\\" + "_")
                    .replace("'", "\\" + "'")
                    .replace("\"", "\\" + "\"");
        }

        return param;
    }


}
